/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.dc.task;

import akka.actor.ActorRef;
import com.cxhd.dc.DataConfig;
import com.cxhd.dc.actor.ActorManager;
import com.cxhd.dc.tool.FileUtil;
import com.google.common.io.Files;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class SendPacsTask_back extends BaseTask {

    private File[] fileDicomFolder;
    private static final org.apache.log4j.Logger logger1 = org.apache.log4j.Logger.getLogger("FileToZip");

    ActorManager actorManager = ActorManager.getIntance();

    @Override
    public BaseTask start() {

        fileDicomFolder = new File(DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getDicomSendFolder()).listFiles();
        return this;
    }

    @Override
    public BaseTask doTask() {
        logger1.info(DataConfig.getInstance().getAET() + "@" + DataConfig.getInstance().getAe_ip() + ":" + DataConfig.getInstance().getAe_port());
        if (FileUtil.testPacs(DataConfig.getInstance().getAe_ip(), DataConfig.getInstance().getAe_port()) && fileDicomFolder != null) {

            for (File file : fileDicomFolder) {
                if (file.isDirectory() && file.list().length > 0) {
                    sendPacs(file);
                }
            }
        } else {
            System.out.println("连接不上PACS服务器");
        }
        return this;
    }

    @Override
    public BaseTask stop() {
        return this;
    }

    public void sendPacs(File f) {
        try {
            Runtime r = Runtime.getRuntime();
            String device = f.getName();
            logger1.info(device);
            File moveFile = null;
            if (checkFileDelete(device)) {
                moveFile = new File(DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getMoveFileFolder() + device + "/");
                moveFile.mkdirs();
            }
            File sendFile = new File(f.getAbsolutePath() + "/" + new Date().getTime() + "/");
            sendFile.mkdirs();
            for (File s : f.listFiles()) {
                if (s.isFile()) {
                    // System.out.println(s.getAbsolutePath()+"-------------"+sendFile.getAbsolutePath() + "/" + s.getName());
                    //修改文件的sopiuid
                    
                    if (moveFile != null) {
                        Files.copy(s, new File(moveFile.getAbsolutePath() + "/" + s.getName()));
                    }else{
                        editSopIuid(s, device, f.getAbsolutePath());
                    }
                    
                    Files.move(s, new File(sendFile.getAbsolutePath() + "/" + s.getName()));

                }
            }
            //  checkDevice(device, newFloder.getAbsolutePath());
            boolean flag = false;
            Process p = r.exec("cmd.exe /c C:\\dcmsyst\\tool-2.0.26\\bin\\dcmsnd -device " + device + " " + DataConfig.getInstance().getAET() + "@" + DataConfig.getInstance().getAe_ip() + ":" + DataConfig.getInstance().getAe_port() + " " + sendFile.getAbsolutePath() + "   -set 00100021= \"Atlas\" -set 00080005= \"GB18030\" -set 00080080=\"" + FileUtil.getSNtoHospitalName(device) + "\"");
            //logger.info("cmd.exe /c C:\\dcmsyst\\tool-2.0.26\\bin\\dcmsnd -device " + device + " " + this.pacsInfo[2] + "@" + this.pacsInfo[0] + ":" + this.pacsInfo[1] + " " + newFloder.getAbsolutePath() + " -set 00080005= \"GB18030\" -set 00080080=\"" + ApProperties.getSNtoHospitalName(device) + "\"");
            //System.out.println("cmd.exe /c C:\\dcmsyst\\tool-2.0.26\\bin\\dcmsnd -device " + device + " " + this.pacsInfo[2] + "@" + this.pacsInfo[0] + ":" + this.pacsInfo[1] + " " + s.getAbsolutePath());
            //writeText("c:/dcmsyst/send.txt", "cmd.exe /c C:\\dcmsyst\\tool-2.0.26\\bin\\dcmsnd -device " + device + " " + this.pacsInfo[2] + "@" + this.pacsInfo[0] + ":" + this.pacsInfo[1] + " " + newFloder.getAbsolutePath());

            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String msg = null;
            while ((msg = br.readLine()) != null) {
                // logger1.info(msg);
                // System.out.println("info msg : " + msg);
            }
            BufferedReader er = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            String error = null;
            while ((error = er.readLine()) != null) {
                logger1.error(error);
                flag = true;

            }
            //p.waitFor();
            p.destroy();

            if (!flag) {
                if (DataConfig.getInstance().getCacheServer() != null) {
                    actorManager.getActor("SendCacheServerActor").tell(device + "@" + sendFile.getAbsolutePath(), ActorRef.noSender());
                } else {
                    for (File del : sendFile.listFiles()) {
                        //System.out.println("K:/dicomTest/" + del.getName());

                        del.delete();
                    }
                }
                sendFile.delete();
//                            newFloder.renameTo(new File(ApProperties.getBasePath() + "sendBackup/" + newFloder.getName()));
//                            list.remove(newFloder.getAbsolutePath());
//
//                            removeDirectory(newFloder);
            }

        } catch (IOException ex) {

        }
    }

    @Override
    public BaseTask cancelTask() {
        return this;
    }

    private void editSopIuid(File s, String device, String path) {
        try {
            String lastChar = device.substring(device.length() - 4, device.length());
            String sopiuid = s.getName().replaceAll("[a-zA-Z]", "") + lastChar;
            String filePath = path + "/" + sopiuid;
            Runtime r = Runtime.getRuntime();

            Process p = r.exec("c:/cxhd2015/tools/dcmodify.exe -nb +fo -m 0008,0018=" + sopiuid + " " + s.getAbsolutePath());

            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String msg = null;
            while ((msg = br.readLine()) != null) {

            }
            BufferedReader er = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            String error = null;
            while ((error = er.readLine()) != null) {
                logger1.error(error);

            }
            //p.waitFor();
            p.destroy();
        } catch (Exception e) {
        }

    }

    public boolean checkFileDelete(String device) {
        String sns = DataConfig.getInstance().getMoveFile_sn();
        if (sns != null) {
            String sn[] = sns.split(",");
            for (String s : sn) {
                if (s.equals(device)) {
                    return true;
                }
            }
        }
        return false;
    }

}
